
package com.wobaby.security;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

import com.wobaby.util.Constants;
import com.wobaby.util.log.Log;
import com.wobaby.util.log.LogPrinter;
import com.wobaby.vo.RoleVO;

// Referenced classes of package com.wobaby.security:
//            ViewPermissions, PermissionMatrix, PermissionEntry

public abstract class Privileges
{

    public Privileges()
    {
    }

    void loadPermissions(Collection roles)
    {
        LogPrinter lp = Log.getLog("auth");
        actionPermissions = new HashSet(100);
        Iterator it = roles.iterator();
        do
        {
            if(!it.hasNext())
                break;
            RoleVO role = (RoleVO)it.next();
            if(lp.configuredFor(0))
            {
                Log.getLog("auth").trace(this, "Got Role : " + role + " roleType:[" + role.getRoleType() + "]");
                Log.getLog("auth").trace(this, "Role's resource collection : " + role.getResourceCollection());
            }
            if(role.getRoleID().equals(Constants.ADMINISTRATOR_ROLE_ID))
            {
                administrator_flag = true;
               
            } else{
            
            String roleType = role.getRoleType().trim();
            if("COMMAND".equals(roleType))
                actionPermissions.addAll(role.getResourceCollection());  
            }
        } while(true);

        if(lp.configuredFor(0))
        {
            Log.getLog("auth").trace(this, "Action permissions : " + actionPermissions.size());
           
        }
    }

    public String getActionPermission(String actionName)
    {
        if(actionPermissions == null)
            return null;
        if(actionPermissions.contains(actionName + "=Y"))
            return "Y";
        if(actionPermissions.contains(actionName + "=O"))
            return "O";
        LogPrinter lp = Log.getLog("auth");
        if(lp.configuredFor(0))
        {
            Log.getLog("auth").trace(com.wobaby.security.UserPermissions.class, "getActionPermission(" + actionName + ") failed");
            String s = "";
            for(Iterator it = actionPermissions.iterator(); it.hasNext();)
                s = s + "[" + it.next() + "]; ";

            Log.getLog("auth").trace(com.wobaby.security.UserPermissions.class, "Granted actions are : " + s);
        }
        return null;
    }

    public boolean hasCommandPermission(String commandName)
    {
        PermissionEntry actionEntry = PermissionMatrix.getActionByName(commandName);
        if(actionEntry == null)
            return false;
        else
            return getActionPermission(actionEntry.name) != null;
    }


    public Collection getActionPermissions()
    {
        return actionPermissions;
    }

    public boolean isAdministrator()
    {
        return administrator_flag;
    }

    protected Collection actionPermissions;
    protected boolean administrator_flag;
}